package com.example.keshe0337.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.keshe0337.R;
import com.example.keshe0337.adapter.ParkingSpaceAdapter;
import com.example.keshe0337.biz.RecordService;
import com.example.keshe0337.biz.SpaceService;
import com.example.keshe0337.entity.ParkingSpace;
import com.example.keshe0337.ui.LoginActivity;
import com.example.keshe0337.utils.GetTypeNumber;

import java.util.List;
import java.util.Locale;

public class AllParkingFragment extends Fragment {
    ListView listView;
    Long UID;
    boolean UM;
    ParkingSpaceAdapter parkingSpaceAdapter;
    Context context;
    SpaceService spaceService;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view0 = inflater.inflate(R.layout.fragment_all_parking, container, false);
        listView = view0.findViewById(R.id.listView);  // 用 view 来查找 ListView
        context = getContext();
        if (context == null) {
            Log.d("TEXT","AllParkingFragment的context为空");
            return view0;
        }

        SharedPreferences prefs = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);

        spaceService = new SpaceService(context);
        List<ParkingSpace> allPSs = spaceService.getAllPSs();
        for (ParkingSpace p :allPSs) {
            Log.d("TEXT",p.getSpaceNum());
        }

        parkingSpaceAdapter = new ParkingSpaceAdapter(context,allPSs);
        listView.setAdapter(parkingSpaceAdapter);

        Button btn = view0.findViewById(R.id.searchButton);
        View text = view0.findViewById(R.id.searchEditText);

        UM = prefs.getBoolean("manager",false);
        ImageButton button1 = view0.findViewById(R.id.addButton);
        ImageButton button2 = view0.findViewById(R.id.quitButton);

        if (UM) {

            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.VISIBLE);
        } else {
            button1.setVisibility(View.GONE);
            button2.setVisibility(View.GONE);
        }

        button1.setOnClickListener(v -> {
            showManageAddDialog();
        });

        button2.setOnClickListener(v -> {
            Intent intent = new Intent(context, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        });


        btn.setOnClickListener(v -> {
            String searchText = "";
            if (text instanceof EditText) {
                EditText editTextPlate = (EditText) text;
                searchText = editTextPlate.getText().toString().trim();
            }
            if (searchText.isEmpty()) {
                parkingSpaceAdapter.update(spaceService.getAllPSs());
            } else {
                List<ParkingSpace> parkingSpaces = spaceService.getPSBySearch(searchText);
                parkingSpaceAdapter.update(parkingSpaces);
            }
        });

        listView.setOnItemClickListener((parent, view, position, id) -> {
            ParkingSpace parkingSpace = parkingSpaceAdapter.getItem(position);
            if (parkingSpace != null) {
                UID = prefs.getLong("UID", 1);
                boolean um = prefs.getBoolean("manager",false);
                Log.d("所有停车位","id="+UID+";status manager="+um);
                if (um) {
                    showManageOptionDialog(parkingSpace);
                } else {
                    showUserOptionDialog(parkingSpace);
                }
            }
        });
        return view0;
    }

    private void showUserOptionDialog(ParkingSpace parkingSpace) {
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_ps_option_user, null);
        TextView parkingNumberText = dialogView.findViewById(R.id.textParkingNumber);
        TextView statusText = dialogView.findViewById(R.id.textStatus);
        TextView locationText = dialogView.findViewById(R.id.textLocation);
        TextView typeText = dialogView.findViewById(R.id.textType);
        TextView feePerHourText = dialogView.findViewById(R.id.textFeePerHour);

        parkingNumberText.setText(parkingSpace.getSpaceNum());
        statusText.setText(parkingSpace.isStatus() ? "空闲" : "占用");
        locationText.setText(parkingSpace.getLocation());
        typeText.setText(parkingSpace.getType());
        feePerHourText.setText(String.format(Locale.CHINA, "%.2f 元/小时",parkingSpace.getHourlyFee()));

        Button btn = dialogView.findViewById(R.id.btn_action);
        View text = dialogView.findViewById(R.id.editTextPlate);


        if (!UID.equals(-1L) && parkingSpace.isStatus()) {
            text.setVisibility(View.VISIBLE);
            btn.setVisibility(View.VISIBLE);

        } else  {
            text.setVisibility(View.GONE);
            btn.setVisibility(View.GONE);
        }

        AlertDialog dialogHolder = new AlertDialog.Builder(context)
                .setView(dialogView)
                .create();
        btn.setOnClickListener(V->{
            if (text instanceof EditText) {
                EditText editTextPlate = (EditText) text;
                String plateNumber = editTextPlate.getText().toString().trim();

                // 弹出确认对话框
                new AlertDialog.Builder(context)
                        .setTitle("确认租借")
                        .setMessage("是否确认租借该车位？\n停车位：" + parkingSpace.getSpaceNum())
                        .setPositiveButton("确认", (dialog, which) -> {
                            // 用户点击确认后执行以下操作
                            Log.d("车牌号", "用户输入的车牌号是：" + plateNumber);
                            RecordService recordService = new RecordService(context);
                            int i = recordService.startRent(UID, parkingSpace.getId(), plateNumber);
                            Log.d("开始租借", "服务层返回值：" + i);
                            parkingSpaceAdapter.update(spaceService.getAllPSs());
                            if (i == 0) {
                                Toast.makeText(context, "租借成功", Toast.LENGTH_SHORT).show();
                                dialogHolder.dismiss();
                            } else {
                                if (i == -1) {
                                    Toast.makeText(context, "租借失败，请检查车牌格式", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(context, "租借失败，请重试", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("取消", (dialog, which) -> {

                            dialogHolder.dismiss(); // 手动关闭主对话框

                        })// 用户点击取消则关闭会话
                        .show();
            }
        });
        dialogHolder.show();
    }

    private void showManageOptionDialog(ParkingSpace parkingSpace) {
        Log.d("操作","管理员");
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_ps_option_manager, null);
        TextView parkingNumberText = dialogView.findViewById(R.id.textParkingNumber);
        TextView statusText = dialogView.findViewById(R.id.textStatus);
        TextView locationText = dialogView.findViewById(R.id.textLocation);
        TextView typeText = dialogView.findViewById(R.id.textType);
        TextView feePerHourText = dialogView.findViewById(R.id.textFeePerHour);

        parkingNumberText.setText(parkingSpace.getSpaceNum());
        statusText.setText(parkingSpace.isStatus() ? "空闲" : "占用");
        locationText.setText(parkingSpace.getLocation());
        typeText.setText(parkingSpace.getType());
        feePerHourText.setText(String.format(Locale.CHINA, "%.2f 元/小时",parkingSpace.getHourlyFee()));

        Button delete_btn = dialogView.findViewById(R.id.btn_action0);
        Button update_btn = dialogView.findViewById(R.id.btn_action1);

        AlertDialog dialogHolder = new AlertDialog.Builder(context)
                .setView(dialogView)
                .create();
        delete_btn.setOnClickListener(v -> {
            spaceService.deleteParkingSpace(parkingSpace.getId());
            parkingSpaceAdapter.update(spaceService.getAllPSs());
            Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
            dialogHolder.dismiss();
        });

        update_btn.setOnClickListener(v -> {
            showUpdate(parkingSpace);
            dialogHolder.dismiss();
        });
        dialogHolder.show();
    }

    private void showUpdate(ParkingSpace parkingSpace) {
        Log.d("管理员","修改");
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_input_ps, null);

        EditText parkingNumberText = dialogView.findViewById(R.id.textParkingNumber);
        EditText priceEditText = dialogView.findViewById(R.id.textPrice);
        EditText locationEditText = dialogView.findViewById(R.id.textLocation);
        Spinner spinner = dialogView.findViewById(R.id.spinnerVehicleType);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                context,
                android.R.layout.simple_spinner_item,
                new String[]{"小型车位", "中型车位", "大型车位"}
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        parkingNumberText.setText(parkingSpace.getSpaceNum());
        priceEditText.setText(parkingSpace.getHourlyFee()+"");
        locationEditText.setText(parkingSpace.getLocation());
        int defaultPosition = adapter.getPosition(parkingSpace.getType());
        spinner.setSelection(defaultPosition);
        Log.d("类型选择","int:"+defaultPosition);



        AlertDialog dialogHolder = new AlertDialog.Builder(context)
                .setView(dialogView)
                .create();

        Button btn = dialogView.findViewById(R.id.buttonSubmit);
        btn.setOnClickListener(v -> {
            String selectedType = spinner.getSelectedItem().toString();
            String parkingNumber = parkingNumberText.getText().toString().trim();
            String price = priceEditText.getText().toString().trim();
            String location = locationEditText.getText().toString().trim();
            if (parkingNumber.isBlank() || price.isBlank() ||location.isBlank()) {
                Toast.makeText(context, "更改失败，请检查信息完整性", Toast.LENGTH_SHORT).show();
                return;
            }
            parkingSpace.setType(selectedType);
            parkingSpace.setSpaceNum(parkingNumber);
            parkingSpace.setHourlyFee(Double.parseDouble(price));
            parkingSpace.setLocation(location);
            int i = spaceService.updateParkingSpace(parkingSpace);
            if (i == 0) {
                Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
                parkingSpaceAdapter.update(spaceService.getAllPSs());
            } else if (i == 2){
                Toast.makeText(context, "该停车位号已存在", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context, "更改失败", Toast.LENGTH_SHORT).show();
            }

            dialogHolder.dismiss();
        });

        dialogHolder.show();
    }

    private void showManageAddDialog() {
        Log.d("管理员","添加");
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_input_ps, null);

        EditText parkingNumberText = dialogView.findViewById(R.id.textParkingNumber);
        EditText priceEditText = dialogView.findViewById(R.id.textPrice);
        EditText locationEditText = dialogView.findViewById(R.id.textLocation);
        Spinner spinner = dialogView.findViewById(R.id.spinnerVehicleType);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                context,
                android.R.layout.simple_spinner_item,
                new String[]{"小型车位", "中型车位", "大型车位"}
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        AlertDialog dialogHolder = new AlertDialog.Builder(context)
                .setView(dialogView)
                .create();
        Button btn = dialogView.findViewById(R.id.buttonSubmit);
        btn.setOnClickListener(v -> {
            ParkingSpace parkingSpace = new ParkingSpace();
            String selectedType = spinner.getSelectedItem().toString();
            String parkingNumber = parkingNumberText.getText().toString().trim();
            String price = priceEditText.getText().toString().trim();
            String location = locationEditText.getText().toString().trim();
            if (parkingNumber.isBlank() || price.isBlank()) {
                Toast.makeText(context, "添加失败，请检查信息完整性", Toast.LENGTH_SHORT).show();
                return;
            }
            parkingSpace.setType(selectedType);
            parkingSpace.setSpaceNum(parkingNumber);
            parkingSpace.setHourlyFee(Double.parseDouble(price));
            parkingSpace.setLocation(location);
            int i = spaceService.addParkingSpace(parkingSpace);
            if (i == 0) {
                Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
                parkingSpaceAdapter.update(spaceService.getAllPSs());
                dialogHolder.dismiss();
            }
            if (i == 2){
                Toast.makeText(context, "添加失败，该停车位已存在", Toast.LENGTH_SHORT).show();
            }
        });
        dialogHolder.show();
    }
}
